<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function showTree()
	{
		$documents = Document::paginate(10);
		return View::make('tree.index')->with(['documents' => $documents]);
	}
	
	public function showWelcome()
	{
		return View::make('hello');
	}

    public function showSecret()
    {
		$categories = Category::all();
		$categoriesHelper = new CategoriesHelper($categories);
		
		//Log::info('$rest = '.substr("abcdef", 0, -1));
		
		//Log::info('JSON LIST :: ' . $categoriesHelper->jsonList());
		
		return '['.$categoriesHelper->jsonList().']';
		//return View::make('secret', compact('categories','categoriesHelper'));
    }    
	
	public function treeContent2()
    {
		$category = Category::where('parent_id', '=', '0')->first();
		
		//Log::info('$rest = '.substr("abcdef", 0, -1));
		
		Log::info('JSON LIST :: ' . $category->id);
		
		return '[{"title":"' . $category->name . '", "key":"' . $category->id . '", "expanded": true, "folder": true, "children": ['.HomeController::jsonList2($category).'] } ] ';
		//return View::make('secret', compact('categories','categoriesHelper'));
    }
	
	
	public function treeContent3()
    {
		$category = Category::find(1);
		
		//Log::info('$rest = '.substr("abcdef", 0, -1));
		
		Log::info('JSON LIST :: ' . $category->id);
		
		return '[{"title":"/", "key":"1", "expanded": true, "folder": true, "children": ['.HomeController::jsonList3($category).'] } ] ';
		//return View::make('secret', compact('categories','categoriesHelper'));
    }

	public static function jsonList2($category) {
	  $html = '';
      foreach($category->children as $children) {
        $html .= '{';
        $html .= '"title":"'.$children->name.' (' . count($children->templates) . ')", "key":"'.$children->id.'", "expanded": true, "folder": true';
		
        if(count($children->children) > 0) {
			$html .= ', "children": [';
			$html .= HomeController::jsonList2($children);
			if (count($children->templates)) {
				$html2 = ', ';
				foreach($children->templates as $template) {
					$html2 .= '{"title":"'.$template->template_name . '", "key":"'.$template->id.'", "refKey":"TEMPLATE"},';
				}
				$html .= substr($html2, 0, -1);
			}
			$html .= ']} ,';
        } else if (count($children->templates)) {
			$html .= ', "expanded": true, "folder": true, "children": [';
			$html2 = '';
			foreach($children->templates as $template) {
				$html2 .= '{"title":"'.$template->template_name . '", "key":"'.$template->id.'", "refKey":"TEMPLATE"},';
			}
			$html .= substr($html2, 0, -1);
			$html .= ']} ,';
		} else {
			$html .= '} ,';
		}
      }	  
      return substr($html, 0, -1);
    }
	
	
    public function showCollapse()
    {
        //return View::make('collapse');
		return View::make('treeview');
    }
	
	

    public function generatePDF($id)
    {
		$user = Auth::User();
		$password = $user->department->pdf_password;
		
		$img_path = storage_path() . '/temp/' . $user->username . '/';
		
		// Load document per document id
		$filename = HomeController::loadDocument($img_path, $id, $user->username);
		
		// Convert tiff to jog
		HomeController::convertTiff2Jpg($filename, $img_path);
		
		// Generate PDF
		$filename = HomeController::imageToPDF($img_path, 'output', $password);
		
		// delete all file on temp path
		HomeController::deleteAllFile($img_path);
		
		return Response::download($filename);
    }

	private function convertTiff2Jpg($filename, $img_path) {
		Log::info('File name >> ' . $filename);
		Log::info('Image path name >> ' . $img_path);
	
		$output_file = $img_path . 'output.jpg';
		$exec_cmd = 'convert ' . $filename . ' -units PixelsPerInch -density 72 -quality 100 ' . $output_file;
	
		// Convert tiff to jpg
		exec($exec_cmd);
		
	}
	
	private function loadDocument($img_path, $documentId, $username) {
		$document = Document::find($documentId);
		$filename = $img_path . $username . '_temp.tiff';
		
		if (!File::exists($img_path)) {
			File::makeDirectory($img_path, 0755, true);
			file_put_contents($filename, $document->content);
		} else {
			file_put_contents($filename, $document->content);
		}
		
		return $filename;
	}
	
	public function deleteAllFile($img_path) {
		$files = File::files($img_path);
		foreach($files as $file_path) {
			File::delete($file_path);
		}
	}
	
	
    public function showTCPDF()
    {
		$filename = HomeController::testcall();
		return Response::download($filename);
        //return View::make('tcpdf');
    }
	
	public function showGirdSystem() {
        return View::make('gridSystem');
	}
	
	public function testcall()
	{
		
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		$pdf->SetProtection(array('print', 'copy'), 'userPass', 'masterPass', 0, null);

		// Example with public-key
		// To open the document you need to install the private key (tcpdf.p12) on the Acrobat Reader. The password is: 1234
		//$pdf->SetProtection($permissions=array('print', 'copy'), $user_pass='', $owner_pass=null, $mode=1, $pubkeys=array(array('c' => 'file://../config/cert/tcpdf.crt', 'p' => array('print'))));

		// *********************************************************


		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Nicola Asuni');
		$pdf->SetTitle('TCPDF Example 016');
		$pdf->SetSubject('TCPDF Tutorial');
		$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

		// set default header data
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING);

		// set header and footer fonts
		$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA));

		// set default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

		// set margins
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		// set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

		// set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		// set some language-dependent strings (optional)
		if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
			require_once(dirname(__FILE__).'/lang/eng.php');
			$pdf->setLanguageArray($l);
		}

		// ---------------------------------------------------------

		// set font
		$pdf->SetFont('times', '', 16);

		// add a page
		$pdf->AddPage();

		// set some text to print
		$txt = "<<<EOD
		Encryption Example

		Consult the source code documentation for the SetProtection() method.
		EOD";

		// print a block of text using Write()
		$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);


		// ---------------------------------------------------------

		//Close and output PDF document
		Log::info('public_path() >> ' . storage_path());
		$filename = storage_path() . '/test.pdf';
		// $filename = public_path() . '/test.pdf';
		
		$pdf->Output($filename, 'F');
		
		return $filename;
		
		// $pdf = new TCPDF();

		// $pdf->SetPrintHeader(false);
		// $pdf->SetPrintFooter(false);
		// $pdf->AddPage();
		// $pdf->Text(90, 140, 'This is a test');
		// $filename = storage_path() . '/test.pdf';
		// $pdf->output($filename, 'F');

		// return $filename;
		
	}
	
	
	public function imageToPDF($img_file_path, $file_prefix, $password)
	{
	
		// create new PDF document
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		$pdf->SetProtection(array('print', 'copy'), $password, 'masterPass', 0, null);
		$pdf->SetProtection(array('print', 'copy'), '', '', 0, null);
		
		// set document information
		//$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Documentor');
		$pdf->SetTitle('Documentor');

		$pdf->SetPrintHeader(false);
		$pdf->SetPrintFooter(false);
		// set auto page breaks
		$pdf->SetAutoPageBreak(false, 0);

		// set image scale factor
		//$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		$files = File::files($img_file_path);
		foreach($files as $file_path) {
			$file_name = File::name($file_path);
			$file_ext = File::extension($file_path);
			if (Str::startsWith($file_name, $file_prefix)) {
			
				$img_file_name = $img_file_path . $file_name . '.' . $file_ext;
				list($width, $height, $attr) = getimagesize($img_file_name);
				
				Log::info("Width: " .$width." Height: " .$height." Attribute: " .$attr);
				// -------------------------------------------------------------------
				// add a page
				if ($width < $height) {
					$pdf->AddPage('P');
					
					// set JPEG quality
					$pdf->setJPEGQuality(100);
					
					$pdf->Image($img_file_name, 0, 0, 210, 297, 'JPG', '', '', false, 300, '', false, false, 1, false, false, false);
				
				} else {
					$pdf->AddPage('L');
					
					// set JPEG quality
					$pdf->setJPEGQuality(100);
					
					$pdf->Image($img_file_name, 0, 0, 297, 210, 'JPG', '', '', false, 300, '', false, false, 1, false, false, false);
				}

				//Log::info('Add image file name : ' . $img_file_name);
				// Image example with resizing
				//$pdf->Image($img_file_name, 0, 0, 595, 842, 'JPG', '', '', false, 300, '', false, false, 1, false, false, false);
				//$pdf->Image($img_file_name, 0, 0, 210, 297, 'JPG', '', '', false, 300, '', false, false, 1, false, false, false);
			}
		}
		
		//Close and output PDF document
		$filename = storage_path() . '/' . uniqid() . '.pdf';
		
		$pdf->Output($filename, 'I');
		
		return $filename;
	}

}
